package ch.ethz.fcl.output;

import java.io.*;
import java.net.*;

public class UDPClient {
	private static boolean initialized = false;
	private static String hostIP = "localhost";
	
	private static int port = 9876;

	private static DatagramSocket clientSocket = null;
	private static InetAddress IPAddress = null;

	public static void sendUDP(String msg) {
		System.out.println(msg);

		if (!initialized)
			init();

		byte[] sendData = new byte[1024];

		sendData = msg.getBytes();
		DatagramPacket sendPacket = new DatagramPacket(sendData,
				sendData.length, IPAddress, port);
		try {
			clientSocket.send(sendPacket);
		} catch (IOException e) {
			System.out.println("Error sending UDP message");
			e.printStackTrace();
		}

		clientSocket.close();
	}

	private static void init() {
		try {
			clientSocket = new DatagramSocket();
			IPAddress = InetAddress.getByName(hostIP);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}
	}
}